package admin_tag_api

import (
	"blog_go/global"
	"blog_go/models"
	"blog_go/models/res"
	"github.com/fatih/structs"
	"github.com/gin-gonic/gin"
	"github.com/sirupsen/logrus"
)

type TagUpdateReq struct {
	ID    uint64 `json:"id" binding:"required" msg:"请输入id" structs:"-"`
	Title string `json:"title" binding:"required" msg:"请输入标签title" structs:"title"` // 标签的名称
}

func (AdminTagApi) TagUpdate(c *gin.Context) {
	var req TagUpdateReq
	if err := c.ShouldBindJSON(&req); err != nil {
		logrus.Error(err)
		panic(res.ErrorMsg{Err: err, Data: &req})
	}
	// 先查询是否存在
	var tagModel models.TagModel
	// 没查询到数据会有错误
	err := global.DB.Take(&tagModel, req.ID).Error
	if err != nil {
		logrus.Error(err)
		panic(err)
	}
	if tagModel.Title == req.Title {
		res.Ok("修改成功", true, c)
		return
	}
	// 去修改
	update := structs.Map(req)
	err = global.DB.Model(&tagModel).Updates(update).Error
	if err != nil {
		logrus.Error(err)
		panic(err)
	}
	res.Ok("修改成功", true, c)
}
